/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.gui.request;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.URL;
import java.text.NumberFormat;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.GroupLayout.Alignment;

import org.utc.ia04.antsontheweb.antColonyOptimisation.ant.AntAgent;
import org.utc.ia04.antsontheweb.antColonyOptimisation.antColony.AntColonyAgent;
import org.utc.ia04.antsontheweb.gui.request.actionListener.CreateAntActionListener;
import org.utc.ia04.antsontheweb.gui.request.actionListener.CreateAntColonyActionListener;
import org.utc.ia04.antsontheweb.gui.request.actionListener.CreateBigBrotherInterface;
import org.utc.ia04.antsontheweb.gui.request.actionListener.CreateKBAgentActionListener;
import org.utc.ia04.antsontheweb.gui.request.actionListener.CreatePheromoneManagerActionListener;
import org.utc.ia04.antsontheweb.gui.request.actionListener.CreatePoolManagerActionListener;
import org.utc.ia04.antsontheweb.gui.request.actionListener.QuickLaunchActionListener;
import org.utc.ia04.antsontheweb.gui.request.actionListener.StopSimulationActionListener;
import org.utc.ia04.antsontheweb.httprequest.agent.HttpReqPoolManager;
import org.utc.ia04.antsontheweb.knowledgeBase.KnowledgeBaseAgent;


public class InterfaceRequest extends JFrame implements PropertyChangeListener
{	
	private static final long serialVersionUID = 1L;
	private AgentInterfaceRequest myAgent;

	//-------------------------------------- Basic Parameters
	private JTextField inputURLText;
	private JComboBox typeComboBox;
	//-------------------------------------- Advanced Parameters
	private JFormattedTextField nbFourmis;
	private JFormattedTextField nbRessourcesCollectees;
	private JFormattedTextField tick;
	private JFormattedTextField nombreRequester;
	private JFormattedTextField lifeExpectancy;
	private JFormattedTextField lifeExpectancyVar;

	//Listener
	private CreateAntActionListener createAntActionListener;
	private CreateAntColonyActionListener createACActionListener;
	private CreateBigBrotherInterface createBigBrotherActionListener;
	private CreateKBAgentActionListener createKBActionListener;
	private CreatePheromoneManagerActionListener createPheromoneActionListener;
	private CreatePoolManagerActionListener createPoolManagerActionListener;
	
	//Button
	private JButton launchButton;
	private JButton quickLaunchButton;
	private JButton stopButton;
	
	//Answer
	JTextArea answer;
	
	public InterfaceRequest(AgentInterfaceRequest a) throws HeadlessException
	{
		super("Ants On The Web -- Default Client");
		myAgent = a;
		
		initialiseFrame();
		myAgent.addPropertyChangeListener(this);
	}
	
	public AgentInterfaceRequest getMyAgent()
	{
		return myAgent;
	}
	
	public Integer getNbFourmis()
	{
		try
		{
			String res = nbFourmis.getText();
			return Integer.valueOf(res);
		}
		catch(Exception e)
		{
			return Integer.valueOf(AntColonyAgent.DEFAULT_NB_ANTS);
		}
	}
	
	public Integer getTick()
	{
		try
		{
			String res = tick.getText();
			return Integer.valueOf(res);
		}
		catch(Exception e)
		{
			return Integer.valueOf(AntColonyAgent.DEFAULT_TICK);
		}
	}
	
	public Integer getNbCollectedRes()
	{
		try
		{
			String res = nbRessourcesCollectees.getText();
			return Integer.valueOf(res);
		}
		catch(Exception e)
		{
			return Integer.valueOf(AntColonyAgent.DEFAULT_COLLECTED_RESSOURCE_MAX);
		}
	}
	
	public Integer getWebsiteType()
	{
		int res = typeComboBox.getSelectedIndex();
		return Integer.valueOf(res != - 1 ? res : AntColonyAgent.DEFAULT_WEBSITE_TYPE);

	}
	
	public Integer getNbRequester()
	{
		try
		{
			String res = nombreRequester.getText();
			return Integer.valueOf(res);
		}
		catch(Exception e)
		{
			return Integer.valueOf(HttpReqPoolManager.DEFAULT_NB_REQUESTER);
		}
	}
	
	public Long getLifeExtancy()
	{
		try
		{
			String res = lifeExpectancy.getText();
			return Long.valueOf(res);
		}
		catch(Exception e)
		{
			return Long.valueOf(AntAgent.DEFAULT_LIFE_EXTANCY);
		}
	}
	
	public Long getLifeExtancyVar()
	{
		try
		{
			String res = lifeExpectancyVar.getText();
			return Long.valueOf(res);
		}
		catch(Exception e)
		{
			return Long.valueOf(AntAgent.DEFAULT_VARIANCE_LIFE_EXTANCY);
		}
	}
	
	public URL getStartURL() throws Exception
	{
		try
		{
			String res = inputURLText.getText();
			return new URL(res);
		}
		catch(Exception e)
		{
			return new URL(AntColonyAgent.DEFAULT_URL);
		}
	}
	
	public void initialiseFrame()
	{
		//---------- Initialisation frame
		setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
		setLocation(200,20);
		setSize(600, 400);
		setVisible(true);
		
		//---------- Création du TabbedPanel
		JTabbedPane tabbedPane = new JTabbedPane();
		setContentPane(tabbedPane);
		
		//Paramétrisation et lancement de la simulation
		initialiseParametresTab(tabbedPane);
		
		//---------- Création d'agents outils
		initialiseToolAgentTab(tabbedPane);
		
		//Création de l'espace de réponse
		initialisationRep(tabbedPane);
	}
	
	private void initialiseToolAgentTab(JTabbedPane tabbedPane)
	{
		JPanel subPanelTools = new JPanel();
		tabbedPane.addTab("Create Agents", subPanelTools);
		subPanelTools.setLayout(new GridLayout(5,1));
		
		//a) PoolManager
		JPanel subSubPanelPoolManager = new JPanel();
		subPanelTools.add(subSubPanelPoolManager);

		subSubPanelPoolManager.setLayout(new BorderLayout());
		subSubPanelPoolManager.add(new JLabel("Pool Manager"), BorderLayout.WEST);

		JButton createPoolManager = new JButton("CREATE");
		createPoolManagerActionListener = new CreatePoolManagerActionListener(this);
		createPoolManager.addActionListener(createPoolManagerActionListener);
		subSubPanelPoolManager.add(createPoolManager, BorderLayout.EAST);
		
		//a) KB_Agent
		JPanel subSubPanelKBAgent = new JPanel();
		subPanelTools.add(subSubPanelKBAgent);

		subSubPanelKBAgent.setLayout(new BorderLayout());
		subSubPanelKBAgent.add(new JLabel("KB Agent"), BorderLayout.WEST);
		
		JButton createKBAgent = new JButton("CREATE");
		createKBActionListener = new CreateKBAgentActionListener(this);
		createKBAgent.addActionListener(createKBActionListener);
		subSubPanelKBAgent.add(createKBAgent, BorderLayout.EAST);
		
		//c) Pheromone Manager
		JPanel subSubPanelPheromonManager = new JPanel();
		subPanelTools.add(subSubPanelPheromonManager);

		subSubPanelPheromonManager.setLayout(new BorderLayout());
		subSubPanelPheromonManager.add(new JLabel("Pheromone Manager"), BorderLayout.WEST);

		JButton createPheromoneManager = new JButton("CREATE");
		createPheromoneActionListener = new CreatePheromoneManagerActionListener(this);
		createPheromoneManager.addActionListener(createPheromoneActionListener);
		subSubPanelPheromonManager.add(createPheromoneManager, BorderLayout.EAST);
		
		//d) Ants
		JPanel subSubPanelAnts = new JPanel();
		subPanelTools.add(subSubPanelAnts);

		subSubPanelAnts.setLayout(new BorderLayout());
		subSubPanelAnts.add(new JLabel("Ants"), BorderLayout.WEST);
		
		JButton createAnt = new JButton("CREATE");
		createAntActionListener = new CreateAntActionListener(this);
		createAnt.addActionListener(createAntActionListener);
		subSubPanelAnts.add(createAnt, BorderLayout.EAST);

		//f) Big Brother interface
		JPanel subSubPanelBigBrother = new JPanel();
		subPanelTools.add(subSubPanelBigBrother);

		subSubPanelBigBrother.setLayout(new BorderLayout());
		subSubPanelBigBrother.add(new JLabel("Big Brother Interface"), BorderLayout.WEST);
		
		JButton createBigBrother = new JButton("CREATE");
		createBigBrotherActionListener = new CreateBigBrotherInterface(this);
		createBigBrother.addActionListener(createBigBrotherActionListener);
		subSubPanelBigBrother.add(createBigBrother, BorderLayout.EAST);
	}
	
	private void initialisationRep(JTabbedPane tabbedPane)
	{
		answer = new JTextArea("Waiting for answer...");
		tabbedPane.addTab("Answer", answer);
	}
	
	private void initialiseParametresTab(JTabbedPane tabbedPane)
	{
		//-------------------Basic Parameters
		JLabel inputURLLabel = new JLabel("Start URL");
		inputURLText = new JTextField();
		inputURLText.setText(AntColonyAgent.DEFAULT_URL);
		
		JLabel typeLabel = new JLabel("Choose a website Type");
		typeComboBox = new JComboBox();
			typeComboBox.addItem(KnowledgeBaseAgent.BUYING_SITE_NAME);
			typeComboBox.addItem(KnowledgeBaseAgent.OTHER_NAME);
		typeComboBox.setSelectedIndex(AntColonyAgent.DEFAULT_WEBSITE_TYPE);
			
		JPanel basicParametersPanel = new JPanel();
		GroupLayout basicParametersPanelGLO = new GroupLayout(basicParametersPanel);
		basicParametersPanel.setLayout(basicParametersPanelGLO);
		basicParametersPanel.setBorder(BorderFactory.createTitledBorder("Basic Parameters"));

		basicParametersPanelGLO.setAutoCreateGaps(true);
		basicParametersPanelGLO.setAutoCreateContainerGaps(true);

		GroupLayout.SequentialGroup hGroup = basicParametersPanelGLO.createSequentialGroup();
		hGroup.addGroup(basicParametersPanelGLO.createParallelGroup().addComponent(inputURLLabel).addComponent(typeLabel));
		hGroup.addGroup(basicParametersPanelGLO.createParallelGroup().addComponent(inputURLText).addComponent(typeComboBox));
		basicParametersPanelGLO.setHorizontalGroup(hGroup);

		GroupLayout.SequentialGroup vGroup = basicParametersPanelGLO.createSequentialGroup();
		vGroup.addGroup(basicParametersPanelGLO.createParallelGroup(Alignment.BASELINE).addComponent(inputURLLabel).addComponent(inputURLText));
		vGroup.addGroup(basicParametersPanelGLO.createParallelGroup(Alignment.BASELINE).addComponent(typeLabel).addComponent(typeComboBox));
		basicParametersPanelGLO.setVerticalGroup(vGroup);
		
		//-------------------Advanced Parameters
		JLabel nbFourmisLabel = new JLabel("Nb of Ants");
		nbFourmis = new JFormattedTextField(NumberFormat.getIntegerInstance());
		nbFourmis.setText(String.valueOf(AntColonyAgent.DEFAULT_NB_ANTS));
		
		JLabel nbRessourcesCollecteesLabel = new JLabel("Nb of collected Res.");
		nbRessourcesCollectees = new JFormattedTextField(NumberFormat.getIntegerInstance());
		nbRessourcesCollectees.setText(String.valueOf(AntColonyAgent.DEFAULT_COLLECTED_RESSOURCE_MAX));
		
		JLabel tickLabel = new JLabel("Tick time");
		tick = new JFormattedTextField(NumberFormat.getIntegerInstance());
		tick.setText(String.valueOf(AntColonyAgent.DEFAULT_TICK));
		
		JLabel nombreRequesterLabel = new JLabel("Nb of requesters");
		nombreRequester = new JFormattedTextField(NumberFormat.getIntegerInstance());
		nombreRequester.setText(String.valueOf(HttpReqPoolManager.DEFAULT_NB_REQUESTER));

		JLabel lifeExtancyLabel = new JLabel("Esperance de vie");
		lifeExpectancy = new JFormattedTextField(NumberFormat.getIntegerInstance());
		lifeExpectancy.setText(String.valueOf(AntAgent.DEFAULT_LIFE_EXTANCY));
		
		JLabel lifeExtancyVarLabel = new JLabel("Var esperance de vie");
		lifeExpectancyVar = new JFormattedTextField(NumberFormat.getIntegerInstance());
		lifeExpectancyVar.setText(String.valueOf(AntAgent.DEFAULT_VARIANCE_LIFE_EXTANCY));
		
		JPanel advancedParametersPanel = new JPanel();
		GroupLayout advancedParametersGLO = new GroupLayout(advancedParametersPanel);
		advancedParametersPanel.setLayout(advancedParametersGLO);
		advancedParametersPanel.setBorder(BorderFactory.createTitledBorder("Advanced Parameters"));

		advancedParametersGLO.setAutoCreateGaps(true);
		advancedParametersGLO.setAutoCreateContainerGaps(true);

		GroupLayout.SequentialGroup hGroup2 = advancedParametersGLO.createSequentialGroup();
		hGroup2.addGroup(advancedParametersGLO.createParallelGroup()
				.addComponent(nbFourmisLabel)
				.addComponent(nbRessourcesCollecteesLabel)
				.addComponent(tickLabel)
				.addComponent(nombreRequesterLabel)
				.addComponent(lifeExtancyLabel)
				.addComponent(lifeExtancyVarLabel));

		hGroup2.addGroup(advancedParametersGLO.createParallelGroup()
				.addComponent(nbFourmis)
				.addComponent(nbRessourcesCollectees)
				.addComponent(tick)
				.addComponent(nombreRequester)
				.addComponent(lifeExpectancy)
				.addComponent(lifeExpectancyVar));
		advancedParametersGLO.setHorizontalGroup(hGroup2);

		GroupLayout.SequentialGroup vGroup2 = advancedParametersGLO.createSequentialGroup();
		vGroup2.addGroup(advancedParametersGLO.createParallelGroup(Alignment.BASELINE).addComponent(nbFourmisLabel).addComponent(nbFourmis))
				.addGroup(advancedParametersGLO.createParallelGroup(Alignment.BASELINE).addComponent(nbRessourcesCollecteesLabel).addComponent(nbRessourcesCollectees))
				.addGroup(advancedParametersGLO.createParallelGroup(Alignment.BASELINE).addComponent(tickLabel).addComponent(tick))
				.addGroup(advancedParametersGLO.createParallelGroup(Alignment.BASELINE).addComponent(nombreRequesterLabel).addComponent(nombreRequester))
				.addGroup(advancedParametersGLO.createParallelGroup(Alignment.BASELINE).addComponent(lifeExtancyLabel).addComponent(lifeExpectancy))
				.addGroup(advancedParametersGLO.createParallelGroup(Alignment.BASELINE).addComponent(lifeExtancyVarLabel).addComponent(lifeExpectancyVar));
		advancedParametersGLO.setVerticalGroup(vGroup2);
		
		//-------------------Contrôle simulation
		JPanel controlPanel = new JPanel();
		controlPanel.setBorder(BorderFactory.createTitledBorder("Simulation Control..."));
		
		GridLayout controlPanelLayout = new GridLayout(1, 3);
		controlPanel.setLayout(controlPanelLayout);

		launchButton = new JButton("LAUNCH !");
		launchButton.setEnabled(myAgent.isMainController());
		createACActionListener = new CreateAntColonyActionListener(this);
		launchButton.addActionListener(createACActionListener);
		controlPanel.add(launchButton);
		
		quickLaunchButton = new JButton("CREATE TOOL AGENTS !");
		quickLaunchButton.setEnabled(myAgent.isMainController());
		quickLaunchButton.addActionListener(new QuickLaunchActionListener(this));
		controlPanel.add(quickLaunchButton);
		
		stopButton = new JButton("STOP !");
		stopButton.setEnabled(false);
		stopButton.addActionListener(new StopSimulationActionListener(this));
		controlPanel.add(stopButton);
		
		//-------------------Main Panel
		JPanel mainPanel = new JPanel();
		GroupLayout mainPanelGLO = new GroupLayout(mainPanel);
		mainPanel.setLayout(mainPanelGLO);
		mainPanelGLO.setHorizontalGroup(mainPanelGLO.createParallelGroup()
				.addComponent(basicParametersPanel)
				.addComponent(advancedParametersPanel)
				.addComponent(controlPanel) );
		mainPanelGLO.setVerticalGroup(mainPanelGLO.createSequentialGroup()
				.addComponent(basicParametersPanel)
				.addComponent(advancedParametersPanel)
				.addComponent(controlPanel) );
		
		//-------------------Add to tabbed Panel
		tabbedPane.addTab("Simulation", mainPanel);
	}
	
	public void propertyChange(PropertyChangeEvent arg0)
	{
		if(arg0.getPropertyName().equals(AgentInterfaceRequest.ANSWER))
		{
			String[] websites = ((String)arg0.getNewValue()).split(", ");
			String result = "";
			for(int i = 0; i < websites.length; ++i)
				result += websites[i] + "\n";
			answer.setText(result);
		}	
	}
	
	public void stimulateListener()
	{
		createBigBrotherActionListener.actionPerformed(null);
		createKBActionListener.actionPerformed(null);
		createPheromoneActionListener.actionPerformed(null);
		createPoolManagerActionListener.actionPerformed(null);
	}
	
	public void toggleButton()
	{
		if(myAgent.isMainController())
		{
			stopButton.setEnabled(!stopButton.isEnabled());
			launchButton.setEnabled(!launchButton.isEnabled());
			quickLaunchButton.setEnabled(!quickLaunchButton.isEnabled());
		}
	}
}
